﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using SecurityTokenServiceNS;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.ServiceModel.Security.Tokens;
using System.ServiceModel.Dispatcher;

namespace STSConsoleImpleSample
{
    class Program
    {
        static void Main(string[] args)
        {
			try
			{
				List<ServiceHost> hostList = new List<ServiceHost>();
				try
				{
					AddInTool.LoadAddIns();
					Console.WriteLine("AddIns Loaded...\n");

					hostList.Add(new ServiceHost(typeof(STSImplSample)));

					foreach (ServiceHost host in hostList)
					{
//						ConfigureAsymmetricBinding(host.Description.Endpoints.Find(typeof(ISecurityTokenService0502)));
//						ConfigureAsymmetricBinding(host.Description.Endpoints.Find(typeof(ISecurityTokenService13)));
						host.Open();
						foreach (ChannelDispatcher cd in host.ChannelDispatchers)
							foreach (EndpointDispatcher ed in cd.Endpoints)
								Console.WriteLine("Listener = {0}\n    State = {1}", ed.EndpointAddress, cd.State);
					}

					Console.Write("\n\nPress <ENTER> to terminate services");
					Console.ReadLine();
				}
				catch (Exception ex)
				{
					Console.Write(ex.ToString());
				}
				finally
				{
					foreach (ServiceHost host in hostList)
						if (host != null && host.State != CommunicationState.Faulted)
							host.Close();
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine("An unexpected fault was encountered:\n{0}", ex);
			}

		}
		static void ConfigureAsymmetricBinding(ServiceEndpoint stsEndpoint)
		{
			//************* Enabling Asymmetric Proof Token ***********************
			//ServiceEndpoint stsEndpoint = host.Description.Endpoints.Find(typeof(SecurityTokenServiceNS.ISecurityTokenService));
			BindingElementCollection bindingElements = stsEndpoint.Binding.CreateBindingElements();
			SecurityBindingElement sbe = bindingElements.Find<SecurityBindingElement>();
			RsaSecurityTokenParameters rsaParams = new RsaSecurityTokenParameters();
			rsaParams.InclusionMode = SecurityTokenInclusionMode.Never;
			rsaParams.RequireDerivedKeys = false;
			SupportingTokenParameters requirements = new SupportingTokenParameters();
			requirements.Endorsing.Add(rsaParams);
			sbe.OptionalOperationSupportingTokenParameters.Add(Constants.WSTrust.Actions0502.Issue, requirements);
			stsEndpoint.Binding = new CustomBinding(bindingElements);
			//************* Enabling Asymmetric Proof Token ***********************
		}
    }
}
